// 在 Cloud code 里初始化 Express 框架
var fs = require('fs');
var express = require('express');
var app = express();
var avosExpressCookieSession = require('avos-express-cookie-session');

// App 全局配置
app.set('views','cloud/views');  // 设置模板目录
app.set('view engine', 'ejs');  // 设置 template 引擎

app.use(express.bodyParser());  // 读取请求 body 的中间件
//启用cookie
app.use(express.cookieParser('123456'));
//使用avos-express-cookie-session记录登录信息到cookie。
app.use(avosExpressCookieSession({ cookie: { maxAge: 3600000 }}));

require('cloud/controllers/post')(app);
require('cloud/controllers/location')(app);
require('cloud/controllers/user')(app);
require('cloud/controllers/admin')(app);
require('cloud/controllers/login')(app);
require('cloud/controllers/price')(app);
//require('cloud/controllers/image')(app);
require('cloud/controllers/install_pack')(app);

app.all("/app/*",function(req, res, next) {  
	var currentUser = AV.User.current();
	if(currentUser){
		next();
	}else {		
		res.redirect('/login');
	}
}); 

app.get('/', function(req, res) {
	res.redirect('/app/index');
});

app.get('/app/map', function (req,res){
	res.render('map.ejs');
});

app.get('/app/index', function(req, res) {
	var currentUser = AV.User.current();
	currentUser.fetch({
		success: function(user) {
			var usertype = user.get("usertype");
			res.render('index.ejs',{ userObj: user });
			
		},
		error: function(user, error) {
			res.render('error', { message: error.message });		  
		}
	});
});

app.listen({"static": {maxAge: 604800000}});

//在app.listen();之后。
app.use(function(req, res, next){	
    	res.status(404);
    	res.render('error', { message: "请求路径不正确!" });
});